// JavaScript source code
const express = require('express');
const router = express.Router();
const conn = require('../db/connectMysql');
const $sql = require('../db/sqlMap');
const sqlres = require('../middleware/sqlPromise');
const spawn = require("child_process").spawn;

function sep() {
    console.log("=".repeat(50)+'\n');
}

//专题信息
router.post('/topic_search', (req, res) => {
    let part = req.body;
    let sel_sql = $sql.topic.select + " where specialtopic='" + part.specialtopic + "'";

    conn.query(sel_sql, (error, result) => { //查询专题是否存在
        if (error) {
            console.log("专题查询数据库操作出错.");
            console.log(error);sep();
            res.status(500).json({
                statusCode: -1,
                message: "专题查询数据库出错"
            })
        }else{
            if (result.length == 0) { //表示专题不存在
                console.log('专题不存在.');sep();
                res.send({
                    statusCode: 0,
                    message: "专题不存在"
                }); 
            } else {
                console.log('专题存在.');
                const serch_sql = $sql.main_topic.select + " where s_topic_id = ?"; //查询专题下的news_id
                conn.query(serch_sql, result[0].s_topic_id, (err, results) => {
                    if (err) {
                        console.log('查询专题下的news_id出错');
                        console.log(err);sep();
                        res.status(500).json({
                            statusCode: -1,
                            message: "数据库操作出错"
                        });
                    } else {
                        if(results.length == 0){
                            console.log('查找新闻成功，没有对应新闻');sep();
                            res.json({
                                statusCode: 1,
                                message: "查找新闻成功，没有对应新闻",
                                data: []
                            });
                        }else{
                            var ser = $sql.main.topic_select + " where news_id in (";
                            results.forEach(element => {
                                ser += element.news_id + ','
                            });
                            ser = ser.substr(0, ser.length - 1) + ')'
                            try{
                                let tmp = sqlres.getSql(ser)
                                .then(resu => {
                                    console.log('查找新闻成功.');sep();
                                    res.json({
                                        statusCode: 1,
                                        message: "查找新闻成功",
                                        data: resu
                                    });
                                })
                                .catch(err => {
                                    // .catch 返回报错信息
                                    console.log(err);sep();
                                    res.status(500).json({
                                        statusCode: -1,
                                        message: "数据库操作出错"
                                    });
                                })
                            }
                            catch(errs){
                                res.status(500).json({
                                    statusCode: -1,
                                    message: "数据库操作出错"
                                });
                            }
                        }
                    }
                })
            }
        }        
    })
})

//创建专题
router.post('/create_topic',(req,res)=>{
    let part = req.body;
    var add_sql = $sql.main_topic.add;
    const topic_sql = $sql.topic.add;
    let info = part.detail;
    if(info == undefined || info.length == 0){
        info = null;
    }
    conn.query(topic_sql, [part.specialtopic,info], (errrr, resu) => {
        if (errrr) {
            console.log("创建专题数据库操作错误。错误信息为：");
            console.log(errrr);sep();
            res.status(500).json({
                statusCode: -1,
                message: "创建专题数据库操作错误"
            })
        } else { //专题创建完毕，调用聚类函数，获取新闻id
            console.log('创建专题成功。');
            let upstr = JSON.stringify(resu);
            let upjson = JSON.parse(upstr);
            let tpid = upjson.insertId;
            const py = spawn("python3", ['./calc/cluster.py']);
            let chunks = []
            // 获取python返回的值
            py.stdout.on("data", data => chunks.push(data))

            // 当python子进程结束时，输出返回的东西
            py.stdout.on('end', function () {
                try {
                    const data = JSON.parse(Buffer.concat(chunks).toString());
                    console.log("python process end...");
                    console.log("聚类结果:", data);
                    if (Object.keys(data).length == 0) {
                        console.log("聚类完成，聚类结果为空，没有匹配的新闻。");sep();
                        res.json({
                            statusCode: 1,
                            message: "聚类完成，聚类结果为空，没有匹配的新闻。"
                        })
                    } else {
                        for (let key in data) {
                            add_sql += "(" + key + "," + tpid + "),";
                        }
                        add_sql = add_sql.substr(0, add_sql.length - 1);
                        conn.query(add_sql, (er, re) => {
                            if (er) {
                                console.log("加入映射表数据库操作错误。错误信息为：");
                                console.log(er);sep();
                                res.status(500).json({
                                    statusCode: -1,
                                    message: "加入映射表数据库操作错误"
                                })
                            } else {
                                console.log('聚类完成.');sep();
                                res.json({
                                    statusCode: 1,
                                    message: "聚类完成",
                                    data
                                });
                            }
                        })
                    }
                }
                catch (e) {
                    console.error('python子进程出错。');
                    console.error(e);sep();
                    console.log('数据库专题表回滚...\n');
                    let deles = 'delete from topic order by s_topic_id desc limit 1';
                    conn.query(deles,(ero,resul)=>{
                        if(ero){
                            console.error('回滚失败');
                            console.error(ero);sep();
                            res.status(500).json({
                                statusCode: -1,
                                message: "回滚失败"
                            })
                        }else{
                            conn.query('alter table topic auto_increment = 1',(eros,resl)=>{
                                if(eros){
                                    console.error('回滚失败');
                                    console.error(eros);sep();
                                    res.status(500).json({
                                        statusCode: -1,
                                        message: "回滚失败"
                                    })
                                }else{
                                    console.log('回滚完成');sep();
                                    res.status(500).json({
                                        statusCode: -2,
                                        message: "python子进程出错，创建失败"
                                    })
                                }
                            })
                        }
                    })
                }
            });
            cluster = {};
            cluster.search_tag = part.specialtopic;
            if (part.detail == undefined || part.detail.length == 0) {
                cluster.detail = [];
            } else {
                cluster.detail = part.detail.split(' ');
            }
            console.log('cluster: ', cluster);
            console.log('\n聚类进行中...\n');
            // 将数据传给python
            py.stdin.write(JSON.stringify(cluster))
            py.stdin.end()
        }
    })
})

//获取所有专题
router.post('/all_topics', (req, res) => {
    const sql_sql = $sql.topic.select;
    conn.query(sql_sql, (error, results) => {
        if (error) {
            console.error('查询所有专题数据库操作出错。');
            console.error(error); sep();
            res.status(500).json({
                statusCode: -1,
                message: "查询所有专题数据库操作出错"
            })
        } else {
            console.log("成功获取所有专题！"); sep();
            res.json({
                statusCode: 1,
                message: "成功获取所有专题",
                data: results
            });
        }
    })
})

//删除专题
router.post('/delete_topic', (req, res) => {
    const part = req.body;
    const del_sql = "delete from topic where specialtopic = ?";
    conn.query(del_sql, part.specialtopic, (error, results) => {
        if (error) {
            console.error('删除专题数据库操作出错。');
            console.error(error); sep();
            res.status(500).json({
                statusCode: -1,
                message: "删除专题数据库操作出错"
            })
        } else {
            conn.query('alter table topic auto_increment = 1', (er, re) => {
                if (er) {
                    console.error('设置自增数据库操作出错。');
                    console.error(er); sep();
                    res.status(500).json({
                        statusCode: -1,
                        message: "设置自增数据库操作出错"
                    })
                } else {
                    console.log("删除专题成功。"); sep();
                    res.json({
                        statusCode: 1,
                        message: "删除成功"
                    });
                }
            })
        }
    })
})
module.exports = router;